package ide.ccf.ccproject.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import ide.ccf.ccproject.common.Utils;
import ide.ccf.ccproject.translate.Message;
import ide.ccf.ccproject.wizards.pages.ExportSelectFolderWizardPage;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;

public class SetInstall {
	protected Shell shell;  
	protected Object result;
	private Document document;
	final Display display = Display.getDefault();
	public Text tName, tContent;
	public int flag = 0;
	public String scriptName;
	String pathSFolder;
	Table table;
	public SetInstall(Shell parent, Table t) {
        try {
        	pathSFolder = ExportSelectFolderWizardPage.sfoldernamePath_cache;
        	table = t;
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            this.document = builder.newDocument();
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        }
	}
	
	 public Object open(String path) { 
	        createContents(); 
	        setInstall(path);
	        shell.open();  
	        shell.layout();   
	        while (!shell.isDisposed()) {  
	            if (!display.readAndDispatch())  
	                display.sleep();  
	        }  
	        return result;  
	    }  
	 
	 private void setInstall(String path) {
		// TODO 自动生成的方法存根
		 File file = getFile(path);
		 if(file != null)
		 {
			 tName.setText(file.getName());
			 tContent.setText(readToString(file.getAbsolutePath()));
		 }
	}
	 
	 private String readToString(String fileName) {  
	        String encoding = "utf-8";  
	        File file = new File(fileName);  
	        Long filelength = file.length();  
	        byte[] filecontent = new byte[filelength.intValue()];  
	        try {  
	            FileInputStream in = new FileInputStream(file);  
	            in.read(filecontent);  
	            in.close();  
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	        try {  
	            return new String(filecontent, encoding);  
	        } catch (UnsupportedEncodingException e) {  
	            System.err.println("The OS does not support " + encoding);  
	            e.printStackTrace();  
	            return null;  
	        }  
	    } 

	private File getFile(String path) {
		//查找该目录下是否有安装脚本文件
			File dir = new File(path);
			File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
			if (files != null) {
			for (int i = 0; i < files.length; i++) {
			String fileName = files[i].getName();
			if (fileName.endsWith("install")) { // 判断文件名是否以.install结尾
				return files[i];
			} }}
			return null;		
	}

	private void createContents() {
		  shell = new Shell(display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);  
	      shell.setSize(550, 650);  
	      shell.setText(Message.ExportSetInfoWizardPage_1);  
	      shell.setLayout(new FillLayout());
	      
	      final ScrolledComposite sc =  new ScrolledComposite(shell, SWT.H_SCROLL  
	                | SWT.V_SCROLL | SWT.BORDER);  
	      final Composite c = new Composite(sc, SWT.NONE);  
	      sc.setContent(c);  
	      GridLayout layout = new GridLayout();  
	      layout.numColumns = 1;  
	      c.setLayout(layout);  
	      
	      //脚本信息
	      final Group g_script = new Group(c, SWT.NONE);
		  g_script.setText("脚本信息");
		  GridData gd_script = new GridData(GridData.FILL_BOTH);
		  gd_script.horizontalSpan = 1;
		  g_script.setLayoutData(gd_script);
		  GridLayout layout_script = new GridLayout(2,false);
		  layout_script.verticalSpacing = 20;
		  g_script.setLayout(layout_script);
		  Label name = new Label(g_script, SWT.NONE);
		  name.setText("脚本名称：");
		  tName = new Text(g_script, SWT.BORDER);
		  tName.setMessage("名字为：软件英文名＋ .install");

		  Label content = new Label(g_script, SWT.NONE);
		  content.setText("脚本内容：");
		  tContent = new Text(g_script, SWT.BORDER | SWT.MULTI| SWT.WRAP| SWT.V_SCROLL);
		  GridData gdText = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
	      gdText.heightHint = 450;
	      tContent.setLayoutData(gdText);
	      String strContent = "#!/bin/bash\n"
			//+"\r\n"
			//+"#在Deb解包之前，将会运行该脚本\r\n"
			+"pre_install()\n"
			+"{\n"
			+" :\n"
			+"}\n"
			//+"#负责完成安装包时的配置\r\n"
			+"post_install()\n"
			+"{\n"
			+" :\n"
			+"}\n"
			//+"#负责停止与软件包相关联的daemon服务\r\n"
			+"pre_remove()\n"
			+"{\n"  
			+" :\n"    
			+"}\n"  
			//+"#负责修改软件包连接或文件关联\r\n"  
			+"post_remove()\n"  
			+"{\n"  
			+" :\n"    
			+"}\n"  
			+"pre_upgrade()\n"  
			+"{\n"  
			+" :\n"    
			+"}\n"  
			+"post_upgrade()\n"  
			+"{\n"  
			+" :\n"    
			+"}\n"  
			+"pre_downgrade()\n"  
			+"{\n"  
			+" :\n"     
			+"}\n"  
			+"post_upgrade()\n"  
			+"{\n"  
			+" :\n"    
			+"}\n"; 
	      
	      tContent.setText(strContent);
		  
		   Composite s = new Composite(c, SWT.NONE);
	        GridData gd_s = new GridData(GridData.FILL_BOTH);
			s.setLayoutData(gd_s);
			GridLayout layout_s= new GridLayout(4,false);
			layout_s.verticalSpacing = 7;
			layout_s.horizontalSpacing = 80;
			s.setLayout(layout_s);
			Label occupy1 = new Label(s, SWT.NONE);
			occupy1.setText("");
			Label occupy2 = new Label(s, SWT.NONE);
			occupy2.setText("");
			Button s_1  = new Button(s, SWT.PUSH);
			s_1.setText("取  消");
			s_1.addSelectionListener(new SelectionAdapter()
			{
				@Override
				public void widgetSelected(SelectionEvent e) {
					flag = 0;
					close();
				}
			});
			Button s_2 = new Button(s, SWT.PUSH);
			s_2.setText("生  成");
			s_2.addSelectionListener(new SelectionAdapter()
			{
				@Override
				public void widgetSelected(SelectionEvent e) {
					pathSFolder = ExportSelectFolderWizardPage.sfoldernamePath_cache;
					 scriptName = tName.getText().trim();
					 Utils.generalCPK(pathSFolder);
			         MessageBox messageBox =   
			        			   new MessageBox(shell,   
			        			    SWT.OK|   
			        			    SWT.CANCEL|   
			        			    SWT.ICON_WARNING);
				        if(!scriptName.isEmpty() && scriptName.endsWith("install"))
				        {
					        String str=pathSFolder + "/CPK/"+tName.getText().trim();
					        createInstall(str, tContent.getText().trim());
					        flag = 1;
					        close();
				        }
				        else if(scriptName.isEmpty())
				        { 
		        			 messageBox.setMessage("文件名不能为空！");   
		        			 messageBox.open();  
				        }
				        else if(!scriptName.endsWith("install"))
				      {
		        			 messageBox.setMessage("文件名后缀必须是.install！");   
		        			 messageBox.open();  
				      }
				}
			});
		  
		  c.setSize(c.computeSize(500, 580));   
		  s.setSize(s.computeSize(500, SWT.DEFAULT)); 
		  tName.setSize(tName.computeSize(350, 20));
		  tContent.setSize(tContent.computeSize(345, 450));
		  s_1.setSize(s_1.computeSize(100, 30));
		  s_2.setSize(s_2.computeSize(100, 30));
		  occupy1.setSize(occupy1.computeSize(120, 30));
		  occupy2.setSize(occupy2.computeSize(120, 30));
	}

	public void close(){
		 shell.close();
	 }
	
	/**
	 * 创建安装脚本文件
	 * @param fileDirectoryAndName 文件路径和文件名
	 * @param fileContent 文件内容
	 */
	public void createInstall(String fileDirectoryAndName,String fileContent){
		  try{
		   String fileName = fileDirectoryAndName;
		   //创建File对象，参数为String类型，表示目录名
		   File myFile = new File(fileName);
		   //删除所有.install文件并再创建新安装脚本文件
		   deleteFile(pathSFolder + "/CPK/");
		   //调用createNewFile()方法创建新文件
		    myFile.createNewFile();
		 
		   //下面把数据写入创建的文件，首先新建文件名为参数创建FileWriter对象
		   FileWriter resultFile = new FileWriter(myFile);
		   //把该对象包装进PrinterWriter对象
		   PrintWriter myNewFile = new PrintWriter(resultFile);
		   //再通过PrinterWriter对象的println()方法把字符串数据写入新建文件
		   myNewFile.println(fileContent);
		   resultFile.close();   //关闭文件写入流
		  }catch(Exception ex){
		   System.out.println("无法创建新文件！");
		   ex.printStackTrace();
		  }
		 }

	private void  deleteFile(String string) {
		//查找该目录下是否有安装脚本文件
		File dir = new File(string);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
		for (int i = 0; i < files.length; i++) {
		String fileName = files[i].getName();
		if (fileName.endsWith("install")) { // 判断文件名是否以.install结尾
			files[i].delete();
			 //设置表格数据  
			int n = table.getItemCount();
			for(int j = 0; j < n; ++j)
			{
				 TableItem item = table.getItem(j);
				 if(item.getText().trim().equals(fileName))
				 {
					 item.setText("");
				 }
			} 
		} }}
	}

	public String getScriptName() {
		return scriptName;
	}
	
}
